package com.freesun.shop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freesun.shop.anno.Log;
import com.freesun.shop.param.UserParam;
import com.freesun.shop.service.SysUserService;
import com.freesun.shop.entity.SysUser;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    private static Logger log = LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("用户条件分页")
    @GetMapping("/page")
    @Log(name = "用户条件分页查询")
    public ResponseEntity<IPage<SysUser>> findSysUserByPage(SysUser sysUser, Page<SysUser> page){

        IPage<SysUser> userPage = sysUserService.findSysUserPage(sysUser,page);

        return ResponseEntity.ok(userPage);
    }

    @ApiOperation("批量删除用户")
    @DeleteMapping
    @Log(name = "删除用户")
    public ResponseEntity<Void> delSysUser(@RequestBody List<Long> ids){
        log.info("要删除的用户为:{}",ids);
        sysUserService.deleteUserByIds(ids);
        return ResponseEntity.ok().build();
    }
    @ApiOperation("新增一个用户")
    @PostMapping
    @Log(name = "增加用户")
    public ResponseEntity<Void> addUser(@RequestBody UserParam userParam){
        log.info("新增的用户为:{}",userParam.getUsername());
        sysUserService.addUser(userParam);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/info/{id}")
    @ApiOperation("查询单个用户信息")
    @Log(name = "查询单个用户")
    public ResponseEntity<SysUser> getUserById(@PathVariable("id") Long id){
        SysUser user = sysUserService.getById(id);
        return ResponseEntity.ok(user);
    }
    @PutMapping
    @ApiOperation("修改用户")
    @Log(name = "修改用户")
    //@RequiresPermissions("")
    public ResponseEntity<Void> updateUser(@RequestBody SysUser sysUser){
        sysUserService.updateUser(sysUser);
        SysUser loginUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        //如果用户修改自己需要重新登录
        if(loginUser.getUserId().equals(sysUser.getUserId())){
            SecurityUtils.getSubject().logout();//清除session
        }
        return ResponseEntity.ok().build();

    }
}
